package com.itheima.tlias.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.tlias.dto.AddSubjectDto;
import com.itheima.tlias.dto.CheckSubjectDto;
import com.itheima.tlias.dto.UpdateSubjectDto;
import com.itheima.tlias.entity.Subject;
import com.itheima.tlias.exception.BizException;
import com.itheima.tlias.mapper.SubjectMapper;
import com.itheima.tlias.service.SubjectService;
import com.itheima.tlias.vo.PageBean;
import com.itheima.tlias.vo.SubjectVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
public class SubjectServiceImpl implements SubjectService {
    @Autowired
    private SubjectMapper subjectMapper;

    @Override
    public PageBean<SubjectVo> subjectPage(CheckSubjectDto dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<SubjectVo> subjectPage = subjectMapper.subjectPage(dto);
        return new PageBean<>(subjectPage.getTotal(), subjectPage.getResult());
    }

    @Override
    public void add(AddSubjectDto dto) {
        Subject subj = subjectMapper.selectByName(dto);
        if (subj != null) {
            throw new BizException("学科名重复");
        }
        Subject subject = new Subject();
        BeanUtils.copyProperties(dto, subject);
        subject.setCreateTime(LocalDateTime.now());
        subjectMapper.add(subject);
    }

    @Override
    public SubjectVo selectById(Integer id) {
        SubjectVo subjectVo = subjectMapper.selectById(id);
        return subjectVo;
    }

    @Override
    public void updateSubject(UpdateSubjectDto dto) {
        Subject subj = subjectMapper.selectByName(dto);
        if (subj != null && !Objects.equals(subj.getName(), dto.getName())) {
            throw new BizException("学科名重复");
        }
        Subject subject = new Subject();
        BeanUtils.copyProperties(dto, subject);
        subject.setUpdateTime(LocalDateTime.now());
        subjectMapper.updateSubject(subject);
    }

    @Override
    public void deleteByIds(List<Integer> ids) {
        subjectMapper.deleteByIds(ids);
    }
}
